# -*- coding: utf-8 -*-
'''
Created on 09/nov/2009

@author: sax
'''
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
from django.utils.text import get_text_list
from django.utils.translation import ugettext as _

#from django import forms, template
#from django.contrib.admin import helpers, widgets
#from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_ngettext, model_format_dict

#from django.core.exceptions import PermissionDenied
#from django.db import models, transaction
#from django.db.models.fields import BLANK_CHOICE_DASH
#from django.forms.formsets import all_valid
#from django.forms.models import BaseInlineFormSet, modelform_factory, modelformset_factory, inlineformset_factory

#from django.shortcuts import get_object_or_404, render_to_response
#from django.utils.datastructures import SortedDict

#from django.utils.functional import curry, update_wrapper
#from django.utils.html import escape
#from django.utils.safestring import mark_safe
#from django.utils.text import capfirst, get_text_list
#from django.utils.translation import ugettext as _, ugettext_lazy
#try:
#    set
#except NameError:
#    from sets import Set as set     # Python 2.3 fallback

from xadmin.options.strategies import Strategy
class LoggerStrategy(Strategy):
    def __set__(self, owner, value):
        super(LoggerStrategy, self).__set__(owner, value)

        if value:
            owner.construct_change_message = self.construct_change_message
            owner.log_addition = self.log_addition
            owner.log_change = self.log_change
            owner.log_deletion = self.log_deletion
            owner.message_user = self.message_user
        else:
            owner.construct_change_message = lambda s,a,b,c: None
            owner.log_addition = lambda a,b,c: None
            owner.log_change = lambda a,b,c: None
            owner.log_deletion = lambda a,b,c: None
            owner.message_user = lambda a,b,c: None
            
        
    def construct_change_message(self, request, form, formsets):
        """
        Construct a change message from a changed object.
        """
        change_message = []
        if form.changed_data:
            change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))

        if formsets:
            for formset in formsets:
                for added_object in formset.new_objects:
                    change_message.append(_('Added %(name)s "%(object)s".')
                                          % {'name': added_object._meta.verbose_name,
                                             'object': force_unicode(added_object)})
                for changed_object, changed_fields in formset.changed_objects:
                    change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
                                          % {'list': get_text_list(changed_fields, _('and')),
                                             'name': changed_object._meta.verbose_name,
                                             'object': force_unicode(changed_object)})
                for deleted_object in formset.deleted_objects:
                    change_message.append(_('Deleted %(name)s "%(object)s".')
                                          % {'name': deleted_object._meta.verbose_name,
                                             'object': force_unicode(deleted_object)})
        change_message = ' '.join(change_message)
        return change_message or _('No fields changed.')

    def log_addition(self, request, object):
        """
        Log that an object has been successfully added.

        The default implementation creates an admin LogEntry object.
        """
        from django.contrib.admin.models import LogEntry, ADDITION
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(object).pk,
            object_id       = object.pk,
            object_repr     = force_unicode(object),
            action_flag     = ADDITION
        )

    def log_change(self, request, object, message):
        """
        Log that an object has been successfully changed.

        The default implementation creates an admin LogEntry object.
        """
        from django.contrib.admin.models import LogEntry, CHANGE
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(object).pk,
            object_id       = object.pk,
            object_repr     = force_unicode(object),
            action_flag     = CHANGE,
            change_message  = message
        )

    def log_deletion(self, request, object, object_repr):
        """
        Log that an object has been successfully deleted. Note that since the
        object is deleted, it might no longer be safe to call *any* methods
        on the object, hence this method getting object_repr.

        The default implementation creates an admin LogEntry object.
        """
        from django.contrib.admin.models import LogEntry, DELETION
        LogEntry.objects.log_action(
            user_id         = request.user.id,
            content_type_id = ContentType.objects.get_for_model(self.model).pk,
            object_id       = object.pk,
            object_repr     = object_repr,
            action_flag     = DELETION
        )

    def message_user(self, request, message):
        """
        Send a message to the user. The default implementation
        posts a message using the auth Message object.
        """
        request.user.message_set.create(message=message)
